<template>
  <div class="app-container">
    <div class="app-main">
      <div class="mainName">白蚁灭治任务单</div>
      <div class="btnGroup">
        <el-button type="primary" size="small" @click="add">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="list" border stripe :key="1">
        <el-table-column
          label="序号"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="申请编号" align="center" prop="taskApplyCode" />
        <el-table-column
          label="白蚁防治单位名称"
          align="center"
          prop="controlName"
          min-width="220"
        />
        <el-table-column label="创建日期" align="center" prop="createTime" />
        <el-table-column label="操作员" align="center" prop="operator" />
        <el-table-column label="状态" align="center" prop="applyState">
          <template slot-scope="scope">
            <div>{{ scope.row.applyState === "1" ? "待审核" : "已完成" }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleDetail(scope.row)"
              >详情</el-button
            >
            <el-button type="text" size="small" @click="handleCancel(scope.row)"
              >撤销提交</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </div>
    <TaskCreateDialog
      :value.sync="dialogVisible"
      :taskForm="taskForm"
      :taskId="taskForm.taskId"
      :companyList="companyList"
      :sourceList="sourceList"
      :areaOptions="areaOptions"
      :streetOptions="streetOptions"
      :stKindList="stKindList"
      :radio.sync="radio"
      :fileType="fileType"
      :handleAreaChange="handleAreaChange"
      :onAreaChange="onAreaChange"
      :handleDecimalInput="handleDecimalInput"
      :getPdf="getPdf"
      :cancel="cancel"
      :submitForm="submitForm"
      @open-area-dialog="handleAddArea"
    />
    <TaskDetailDialog
      :value.sync="detailDialogVisible"
      :taskForm="detailTaskForm"
      :taskId="detailTaskForm.taskId"
      :companyList="companyList"
      :sourceList="sourceList"
      :areaOptions="areaOptions"
      :streetOptions="streetOptions"
      :stKindList="stKindList"
      :radio="radio"
      :fileType="fileType"
      :getPdf="getPdf"
      :cancel="cancelDetail"
    />
    <AddAreaDialog
      :value.sync="addAreaVisible"
      :areaTableData.sync="areaTableData"
      @submit="onAddAreaSubmit"
      @cancel="addAreaCancel"
    />
  </div>
</template>
<script>
import { queryMonitorPointTermite } from "@/api/manage/asset";
import {
  getControlCompanyData,
  companyControlTaskQuery,
  addressQuery, // 查询上海地址
} from "@/api/manage/approval";
import AddAreaDialog from "@/views/manage/termiteContral/components/AddAreaDialog.vue";
import TaskCreateDialog from "@/views/manage/termiteContral/components/TaskCreateDialog.vue";
import TaskDetailDialog from "@/views/manage/termiteContral/components/TaskDetailDialog.vue";
export default {
  name: "task",
  components: {
    AddAreaDialog,
    TaskCreateDialog,
    TaskDetailDialog,
  },
  data() {
    return {
      loading: false,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      currentRow: null,
      dialogVisible: false,
      detailDialogVisible: false,
      taskForm: {
        // 基本信息模块
        unitId: "",
        unitName: "",
        source: "",
        addressType: "",
        addressMethod: "",

        // 地址信息模块
        district: "",
        districtId: "",
        street: "",
        streetId: "",
        houseNumber: "",

        // 房屋信息模块
        unitType: "单位",
        companyName: "",
        contactPerson: "",
        contactPhone: "",
        houseType: "",
        houseNature: "",
        buildingArea: "",
        floor: "",

        // 时间信息模块
        applyDate: "",
        appointmentDate: "",
        constructionDate: "",
        acceptanceDate: "",

        // 查勘信息模块
        surveyDate: "",
        houseTypeSurvey: "",
        isTermite: "是",
        isFirstTime: "",
        discoveryLocation: "",

        // 施工信息模块
        isConstruction: "",
        constructionSituation: "",
        constructionReason: "",
        constructionLocation: "",
        constructionArea: "",
        medicineName: "",
        chargeAmount: "",
        termiteSpecies: "",
        otherSpecies: "",
        constructionPersonnel: "",
        constructionDays: "",
        constructionCost: "",
        constructionStatus: "",

        // 验收信息模块
        acceptanceResult: "",
        acceptancePersonnel: "",
        acceptanceOpinion: "",
        userSatisfaction: "",
        qualityEvaluation: "",

        // 其他信息
        name: "",
        img1: "",
        img3: "",
      },
      radio: "系统选择",
      fileType: ["png", "jpg", "jpeg"],
      companyList: [],
      sourceList: [
        { value: "企业自行受理", label: "企业自行受理" },
        { value: "962121受理", label: "962121受理" },
        { value: "其他", label: "其他" },
      ],
      areaOptions: [],
      streetOptions: [],
      stKindList: [
        { value: "01", label: "商品房" },
        { value: "02", label: "动迁房" },
        { value: "03", label: "共有产权保障房" },
        { value: "04", label: "售后房" },
        { value: "05", label: "直管公房" },
        { value: "06", label: "混合" },
        { value: "07", label: "系统公房" },
        { value: "08", label: "集体土地集资房" },
        { value: "09", label: "军产" },
        { value: "10", label: "私产" },
        { value: "11", label: "公租房" },
        { value: "12", label: "廉价房" },
      ],
      addAreaVisible: false,
      areaTableData: [{ area: "", count: "" }],
      detailTaskForm: {
        // 基本信息模块
        unitName: "",
        taskCode: "",
        source: "",
        addressType: "",

        // 地址信息模块
        district: "",
        districtName: "",
        street: "",
        streetId: "",
        houseNumber: "",

        // 房屋信息模块
        unitType: "单位",
        companyName: "",
        contactPerson: "",
        contactPhone: "",
        houseType: "",
        houseNature: "",
        buildingArea: "",
        floor: "",

        // 时间信息模块
        applyDate: "",
        appointmentDate: "",
        constructionDate: "",
        acceptanceDate: "",

        // 查勘信息模块
        surveyDate: "",
        houseTypeSurvey: "",
        isTermite: "是",
        isFirstTime: "",
        discoveryLocation: "",

        // 施工信息模块
        isConstruction: "",
        constructionSituation: "",
        constructionReason: "",
        constructionLocation: "",
        constructionArea: "",
        medicineName: "",
        chargeAmount: "",
        termiteSpecies: "",
        otherSpecies: "",
        constructionPersonnel: "",
        constructionDays: "",
        constructionCost: "",
        constructionStatus: "",

        // 验收信息模块
        acceptanceResult: "",
        acceptancePersonnel: "",
        acceptanceOpinion: "",
        userSatisfaction: "",
        qualityEvaluation: "",

        // 其他信息
        name: "",
        img1: "",
        img3: "",
      },
    };
  },
  watch: {
    radio(newVal, oldVal) {
      // 当系统选择和手动录入切换时，清空小区名称
      if (newVal !== oldVal) {
        this.taskForm.district = "";
        this.taskForm.districtId = "";
        this.taskForm.street = "";
        this.taskForm.streetId = "";
        this.taskForm.houseNature = "";
      }
    },
    "taskForm.addressType"(newVal, oldVal) {
      // 当地址类型切换时，清空小区名称
      if (newVal !== oldVal) {
        this.taskForm.district = "";
        this.taskForm.districtId = "";
        this.taskForm.street = "";
        this.taskForm.streetId = "";
        this.taskForm.houseNature = "";
      }
    },
  },
  mounted() {
    this.getList();
    this.getCompany();
    this.getAddress();
  },
  methods: {
    getAddress() {
      // 查询上海地址
      addressQuery({}).then((res) => {
        if (res.errorCode === "000000") {
          this.areaOptions = res.data;
        }
      });
    },
    // 区改变后获取街道
    onAreaChange(val) {
      addressQuery({ faId: val }).then((res) => {
        if (res.errorCode === "000000") {
          this.streetOptions = res.data;
        }
      });
    },
    getList() {
      this.loading = true;
      companyControlTaskQuery(this.queryParams)
        .then((res) => {
          if (res.errorCode == "000000") {
            this.list = res.data.list;
            this.total = res.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getCompany() {
      getControlCompanyData().then((res) => {
        if (res.errorCode === "000000") {
          this.companyList = res.data;
          this.taskForm.unitId = res.data[0].controlId;
        }
      });
    },
    add() {
      this.taskForm.taskId = null; // 清空任务ID表示新增模式
      this.dialogVisible = true;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    submitForm() {
      // 打印当前表单数据
      console.log("提交表单:", this.taskForm);
    },
    cancel() {
      this.dialogVisible = false;
    },
    // 编辑操作
    handleEdit(row) {
      console.log("编辑:", row);
      this.taskForm.taskId = row.taskId; // 设置任务ID表示编辑模式
      this.dialogVisible = true;
    },
    // 详情操作
    handleDetail(row) {
      console.log("详情:", row);
      // 先重置 taskId，确保 watch 能触发
      this.detailTaskForm.taskId = null;
      // 使用 $nextTick 确保重置完成后再设置新值
      this.$nextTick(() => {
        // 设置详情表单数据
        this.detailTaskForm.taskId = row.taskId;
        // 这里可以根据 row 数据填充详情表单，或者从后端获取详细数据
        this.fillDetailFormData(row);
        this.detailDialogVisible = true;
      });
    },
    // 填充详情表单数据
    fillDetailFormData(row) {
      // 先清空旧数据，确保每次打开都是全新的数据
      // 日期字段应该重置为 null，其他字段重置为空字符串
      const dateFields = [
        "applyDate",
        "appointmentDate",
        "constructionDate",
        "acceptanceDate",
      ];
      Object.keys(this.detailTaskForm).forEach((key) => {
        if (key !== "taskId") {
          if (dateFields.includes(key)) {
            this.detailTaskForm[key] = null;
          } else {
            this.detailTaskForm[key] = "";
          }
        }
      });
      // 根据行数据填充详情表单
      Object.assign(this.detailTaskForm, {
        // 基本信息模块
        unitName: row.controlName || "上海白蚁防治有限公司",
        taskCode: row.taskApplyCode || "TASK-2024-001",
        source: "企业自行受理",
        addressType: "住宅",

        // 地址信息模块
        district: "浦东新区陆家嘴街道",
        districtName: "浦东新区",
        street: "陆家嘴街道",
        streetId: "陆家嘴金融贸易区",
        houseNumber: "123",

        // 房屋信息模块
        unitType: "单位",
        companyName: "上海某公司",
        contactPerson: "张先生",
        contactPhone: "13800138000",
        houseType: "商品房",
        houseNature: "商品房",

        // 时间信息模块
        applyDate: this.parseDateString(row.applyDate || "2024-01-15"),
        appointmentDate: this.parseDateString(
          row.appointmentDate || "2024-01-20",
        ),
        constructionDate: this.parseDateString(
          row.constructionDate || "2024-01-25",
        ),
        acceptanceDate: this.parseDateString(
          row.acceptanceDate || "2024-01-30",
        ),

        // 查勘信息模块
        isTermite: "是",
        discoveryLocation: "客厅、卧室",

        // 施工信息模块
        isConstruction: "否",
        constructionSituation: "已进行白蚁灭治处理",
        constructionReason: "客户要求不进行灭治",
        constructionPersonnel: "李师傅",
        constructionLocationType: "自用",
        constructionArea: "50.5",
        medicineName: "氯氰菊酯",
        chargeAmount: "1200.00",
        termiteSpecies: "散白蚁",
        otherSpecies: "其他蚁种",

        // 验收信息模块
        userSatisfaction: "满意",
        userSignature: "张三",
        acceptanceResult: "验收通过",

        // 其他信息
        name: "白蚁灭治任务单",
        img1: "https://via.placeholder.com/200x150",
        img3: "https://via.placeholder.com/200x150",
      });
    },
    // 关闭详情弹窗
    cancelDetail() {
      this.detailDialogVisible = false;
      // 重置 taskId，确保下次打开时 watch 能触发
      this.$nextTick(() => {
        this.detailTaskForm.taskId = null;
      });
    },
    // 将 yyyy-MM-dd 格式的字符串转换为 Date 对象
    parseDateString(dateString) {
      if (!dateString) return null;
      if (typeof dateString === "string") {
        // 处理 yyyy-MM-dd 格式
        if (dateString.includes("-")) {
          return new Date(dateString);
        }
        // 处理其他格式
        return new Date(dateString);
      }
      return dateString;
    },
    // 撤销提交操作
    handleCancel(row) {
      console.log("撤销提交:", row);
      // TODO: 实现撤销提交逻辑
    },
    async handleAreaChange(selectedArea) {
      if (selectedArea) {
        this.taskForm.district = selectedArea.stNameFrst;
        this.taskForm.districtId = selectedArea.hpbId;
        await this.onAreaChange(selectedArea.hpbId);
        this.taskForm.street = selectedArea.streetId;
        this.taskForm.streetId = selectedArea.stAddrFrst;
        if (selectedArea.stKind) {
          this.taskForm.houseNature = this.getStKindLabel(selectedArea.stKind);
        } else {
          this.taskForm.houseNature = "";
        }
      } else {
        this.taskForm.district = "";
        this.taskForm.street = "";
        this.taskForm.streetId = "";
      }
    },

    // 根据value获取label
    getStKindLabel(value) {
      const item = this.stKindList.find((item) => item.value === value);
      return item ? item.label : "";
    },

    // 根据label获取value
    getStKindValue(label) {
      const item = this.stKindList.find((item) => item.label === label);
      return item ? item.value : "";
    },
    handleAddArea() {
      this.addAreaVisible = true;
    },
    addAreaCancel() {
      this.addAreaVisible = false;
    },
    addAreaSubmit() {
      // 校验是否填写完整
      for (let i = 0; i < this.areaTableData.length; i++) {
        const row = this.areaTableData[i];
        if (!row.area || !row.count) {
          this.$message.error(`第${i + 1}项信息填写不完整，请检查`);
          return;
        }
      }

      // 这里可以处理表格数据的保存逻辑
      this.$message.success("保存成功");
      this.addAreaVisible = false;
    },

    // 新组件提交回调
    onAddAreaSubmit(rows) {
      this.areaTableData = rows;
      this.addAreaSubmit();
    },

    // 处理小数输入，支持两位小数且不能以0开头
    handleDecimalInput(value, field) {
      // 移除所有非数字和小数点的字符
      let cleanValue = value.replace(/[^\d.]/g, "");

      // 不能以0开头（除非是0.xx格式）
      if (
        cleanValue.startsWith("0") &&
        cleanValue.length > 1 &&
        !cleanValue.startsWith("0.")
      ) {
        cleanValue = cleanValue.substring(1);
      }

      // 确保只有一个小数点
      const parts = cleanValue.split(".");
      if (parts.length > 2) {
        cleanValue = parts[0] + "." + parts.slice(1).join("");
      }

      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        cleanValue = parts[0] + "." + parts[1].substring(0, 2);
      }

      this.taskForm[field] = cleanValue;
    },

    // PDF导出方法
    getPdf() {
      this.$getPdf();
    },
  },
};
</script>
<style lang="scss" scoped>
.app-main {
  background-color: #fff;
  // padding: 15px 20px;
  border-radius: 8px;
  .mainName {
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 500;
    font-size: 16px;
    height: 30px;
    line-height: 30px;
    color: #000000;
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }
  .btnGroup {
    text-align: right;
    margin: 15px 0;
  }
}
::v-deep .el-dialog__header {
  border-bottom: 1px solid #e9e9ec;
}
.formBox {
  .left {
    display: inline-block;
    height: 44px;
    line-height: 44px;
    width: 30%;
    padding-right: 15px;
    border-left: 1px solid #e4e4dc;
    border-right: 1px solid #e4e4dc;
    font-family: MicrosoftYaHei;
    font-size: 12px;
    color: #303133;
    text-align: right;
    vertical-align: top;
  }
  .right {
    display: inline-block;
    width: 70%;
    height: 44px;
    border-right: 1px solid #e4e4dc;
    padding: 6px 15px;
    // .el-select {
    //   width: 340px !important;
    // }
    // .el-input {
    //   width: 340px !important;
    // }
  }
  .formHead {
    width: 100%;
    height: 44px;
    background-color: #5d6d7f;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-family: MicrosoftYaHei, MicrosoftYaHei;
    font-weight: bold;
    font-size: 12px;
    color: #ffffff;
  }
  .formWhite {
    width: 100%;
    height: 44px;
    background-color: #fff;
    display: flex;
    .left {
      height: 44px;
      line-height: 44px;
      flex: 3;
      padding-right: 14px;
      border-bottom: 1px solid #e4e4dc;
      font-family: MicrosoftYaHei;
      font-size: 12px;
      color: #303133;
      text-align: right;
      vertical-align: top;
    }
    .right {
      flex: 7;
      height: 44px;
      border-bottom: 1px solid #e4e4dc;
      padding-right: 15px;
    }
  }
  .formGray {
    width: 100%;
    height: 44px;
    background-color: #dbe2e6;
  }
  .white {
    display: flex;
    background-color: #fff;
  }
  .gray {
    display: flex;
    background-color: #eef0f2;
  }
  .ml {
    flex: 3;
    display: flex;
    width: 30%;
    height: 352px;
    border-left: 1px solid #e4e4dc;
    border-right: 1px solid #e4e4dc;
    // border-top: none;
    // border-bottom: none;
    .mlLeft {
      flex: 1;
      border-right: 1px solid #e4e4dc;
      border-bottom: 1px solid #e4e4dc;
      padding-right: 15px;
      text-align: right;
      height: 352px;
      line-height: 352px;
    }

    .mlRight {
      flex: 1;

      .height1 {
        height: 44px;
        line-height: 44px;
        text-align: right;
        border-bottom: 1px solid #e4e4dc;
        padding-right: 15px;
      }
      .height3 {
        height: 132px;
        line-height: 132px;
        text-align: right;
        border-bottom: 1px solid #e4e4dc;
        padding-right: 15px;
      }
    }
  }
  .mr {
    flex: 7;

    .mrRight {
      height: 44px;
      border-right: 1px solid #e4e4dc;
      border-bottom: 1px solid #e4e4dc;
      padding: 6px 15px;
      display: flex;
      gap: 5px;
      .mrRight_left {
        flex: 3;
      }
      .mrRight_right {
        flex: 5;
      }
      .flex2 {
        flex: 2;
      }
    }
    .line3 {
      display: flex;
      height: 132px;
      .line3Left {
        flex: 3;
        display: flex;
        align-items: center;
        // height: 132px;
        // line-height: 132px;
        padding: 0 15px;
        border-right: 1px solid #e4e4dc;
        border-bottom: 1px solid #e4e4dc;
      }
      .line3Right {
        flex: 11;
        .box {
          height: 44px;
          display: flex;
          .box_left {
            flex: 3;
            text-align: right;
            line-height: 44px;
            padding-right: 15px;
          }
          .box_right {
            flex: 5;
            padding: 6px 15px;
          }
        }
        .box2 {
          height: 88px;
          display: flex;
          .box_left {
            flex: 3;
            text-align: right;
            line-height: 88px;
            padding-right: 15px;
          }
          .box_right {
            flex: 5;
            padding: 6px 15px;
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
  .mrr {
    flex: 7;
    display: flex;
    .mrr_left {
      flex: 3;
      padding: 6px 15px;
      display: flex;
      align-items: center;
    }
    .mrr_right {
      flex: 11;
      display: flex;
      flex-direction: column;
      .top {
        flex: 1;
        padding: 6px 15px;
      }
      .bottom {
        flex: 1;
        padding: 6px 15px;
      }
    }
  }
}
.h264 {
  height: 264px !important;
  line-height: 264px !important;
}
.h88 {
  height: 88px !important;
  line-height: 88px !important;
}
.h44 {
  height: 44px !important;
  line-height: 44px !important;
}
.rb {
  border-right: 1px solid #e4e4dc;
  border-bottom: 1px solid #e4e4dc;
}
.b {
  border-bottom: 1px solid #e4e4dc;
}
.formBox {
  ::v-deep .el-select {
    width: 100% !important;
  }
  ::v-deep .el-input {
    width: 100% !important;
  }
}

.mlBox {
  padding-right: 15px;
}
.red {
  color: red;
  margin-right: 5px;
}
.hcenter {
  display: flex;
  align-items: center;
}

.table-header {
  margin-bottom: 15px;
  text-align: left;
}
</style>
